package controller_book

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"tools-api/src/common/utils"
	"tools-api/src/jcj/model"
	"tools-api/src/jcj/service/service_book"
	"tools-api/src/routes/request"
	"tools-api/src/routes/response"
)

// BookAdd 账本新增
func BookAdd(ctx *gin.Context) {
	var req = struct {
		Id         int64
		Name       string
		MonthStart int `json:"month_start"`
	}{}
	_ = ctx.ShouldBindBodyWith(&req, binding.JSON)
	req.Name = utils.Trim(req.Name)
	if req.Name == "" || req.MonthStart < 1 || req.MonthStart > 31 {
		response.Fail(ctx, "参数错误")
		return
	}
	book := model.Book{
		Id:         req.Id,
		Uuid:       request.GetCurrentUser(ctx),
		Name:       req.Name,
		MonthStart: req.MonthStart,
	}
	success, msg := service_book.BookAddOrUpdate(book)
	if success {
		response.SuccessMsg(ctx, msg) // 新增/修改成功
	} else {
		response.Fail(ctx, msg)
	}
}

// BookDelete 单个删除
func BookDelete(ctx *gin.Context) {
	id := utils.Str2Int64(ctx.Param("id"))
	if id <= 0 {
		response.Fail(ctx, "参数错误")
		return
	}
	err := service_book.BookDelete(request.GetCurrentUser(ctx), id)
	if err != nil {
		response.Fail(ctx, "删除失败")
		return
	}
	response.SuccessMsg(ctx, "删除成功")
}

// BookList 我的账本列表
func BookList(ctx *gin.Context) {
	list := service_book.GetBookList(request.GetCurrentUser(ctx))
	response.Success(ctx, list)
}

// BookSetCurrent 设置当前账本
func BookSetCurrent(ctx *gin.Context) {
	var req = struct {
		Id int64 `json:"id"`
	}{}
	if err := ctx.ShouldBindBodyWith(&req, binding.JSON); err != nil {
		response.Fail(ctx, "参数错误")
		return
	}
	if req.Id == 0 {
		response.Fail(ctx, "参数错误")
		return
	}
	err := service_book.BookSetCurrent(request.GetCurrentUser(ctx), req.Id)
	if err != nil {
		response.Fail(ctx, "设置失败")
		return
	}
	response.SuccessMsg(ctx, "设置成功")
}
